package blue.web.commons.service;

import blue.tools.constants.BlueContants;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;

@Configuration
@Service
public class OSSService implements InitializingBean {

    @Value("${blue-erp.oss.endpoint}")
    private  String endpoint;

    @Value("${blue-erp.oss.accessKeyId}")
    private  String accessKeyId;

    @Value("${blue-erp.oss.accessKeySecret}")
    private  String accessKeySecret;

    private OSSClient ossClient;

    private HashMap<String,OSSClient> ossClientMap=new HashMap();

    public  OSSClient getOSSClient(){

        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    public  OSSClient getOSSClient(String region){

        return ossClientMap.get(region);
    }

    public  OSSClient getOSSClient(String endpoint,String accessKeyId,String accessKeySecret){

        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }


    public  boolean putObject(String fileName, InputStream inputStream,String bucketName,OSSClient newOssClient){

        try {
            if(newOssClient==null){
                newOssClient=ossClient;
            }
            newOssClient.putObject(bucketName, fileName,inputStream);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public  InputStream getObject(String fileName, String bucketName,OSSClient newOssClient){

        try {

            if(newOssClient==null){
                newOssClient=ossClient;
            }

            OSSObject ossObject=newOssClient.getObject(bucketName, fileName);

            if(ossObject==null || ossObject.getObjectContent()==null){

                return null;
            }

            return ossObject.getObjectContent();
        }catch (Exception e){
            return null;
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ossClientMap.put(BlueContants.oss_region_shanghai,new OSSClient("http://oss-cn-shanghai.aliyuncs.com", accessKeyId, accessKeySecret));
        ossClientMap.put(BlueContants.oss_region_beijing,new OSSClient("http://oss-cn-beijing.aliyuncs.com", accessKeyId, accessKeySecret));
    }
}
